<template>
  <div class="order-container">
    <!-- 顶部导航栏 -->
    <header class="nav-header">
      <div class="header-left">
        <h1>我的外卖</h1>
      </div>
      <div class="header-right">
        <span class="username">欢迎，{{ currentUser }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <!-- 主体内容 -->
    <main class="order-content">
      <!-- 商家信息 -->
      <div class="restaurant-info">
        <h2>美味餐厅</h2>
        <p class="restaurant-desc">提供各种美食，快速送达</p>
        <div class="restaurant-tags">
          <span class="tag">免费配送</span>
          <span class="tag">新客立减</span>
          <span class="tag">满减优惠</span>
        </div>
      </div>

      <!-- 菜品分类 -->
      <div class="food-categories">
        <button 
          v-for="category in categories" 
          :key="category.id"
          :class="['category-btn', { active: activeCategory === category.id }]"
          @click="switchCategory(category.id)"
        >
          {{ category.name }}
        </button>
      </div>

      <!-- 菜品列表 -->
      <div class="food-list">
        <div v-for="food in currentFoods" :key="food.id" class="food-item">
          <img :src="food.image" :alt="food.name" class="food-image">
          <div class="food-info">
            <h3 class="food-name">{{ food.name }}</h3>
            <p class="food-desc">{{ food.description }}</p>
            <div class="food-bottom">
              <span class="food-price">¥{{ food.price }}</span>
              <div class="food-actions">
                <button class="add-btn" @click="addToCart(food)">+</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 购物车底部栏 -->
      <div class="cart-bar" v-if="cartItems.length > 0">
        <div class="cart-summary">
          <span class="cart-count">购物车({{ cartItems.length }})</span>
          <span class="cart-total">总计: ¥{{ cartTotal }}</span>
        </div>
        <button class="checkout-btn">去结算</button>
      </div>
    </main>
  </div>
</template>

<script>
import { productAPI, cartAPI, userAPI } from '../api/api.js';

export default {
  name: 'Order',
  data() {
    return {
      currentUser: '',
      categories: [],
      activeCategory: null,
      foods: [],
      cartItems: [],
      loading: false
    }
  },
  computed: {
    currentFoods() {
      if (!this.activeCategory) return [];
      return this.foods.filter(food => food.categoryId === this.activeCategory);
    },
    cartTotal() {
      return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
    }
  },
  async mounted() {
    // 检查登录状态
    const user = localStorage.getItem('user');
    if (!user) {
      this.$router.push('/login');
      return;
    }
    
    // 获取用户名
    this.currentUser = JSON.parse(user).username || '用户';
    
    try {
        this.loading = true;
        // 并行请求数据
        const [categoriesData, productsData] = await Promise.all([
          productAPI.getCategories(),
          productAPI.getProducts()
        ]);
        
        // 设置数据
        this.categories = categoriesData;
        this.foods = productsData;
      
      // 设置默认选中第一个分类
      if (this.categories.length > 0) {
        this.activeCategory = this.categories[0].id;
      }
      
      // 获取购物车数据
      await this.fetchCart();
    } catch (error) {
      console.error('加载数据失败:', error);
      alert('加载数据失败，请稍后重试');
    } finally {
      this.loading = false;
    }
  },
  methods: {
    // 获取购物车数据
    async fetchCart() {
      try {
        const user = JSON.parse(localStorage.getItem('user'));
        if (user && user.id) {
          this.cartItems = await cartAPI.getCart(user.id);
        }
      } catch (error) {
        console.error('Failed to fetch cart:', error);
      }
    },
    async handleLogout() {
      try {
        // 使用封装的logout API
        await userAPI.logout();
        // 清除登录状态
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        // 跳转到登录页面
        this.$router.push('/login');
      } catch (error) {
        console.error('退出登录失败:', error);
        // 即使API调用失败，也要清除所有本地登录状态
        localStorage.removeItem('user');
        localStorage.removeItem('token');
        localStorage.removeItem('isLoggedIn');
        this.$router.push('/login');
      }
    },
    switchCategory(categoryId) {
      this.activeCategory = categoryId;
    },
    async addToCart(food) {
      try {
        const user = JSON.parse(localStorage.getItem('user'));
        if (!user || !user.id) {
          alert('请先登录');
          this.$router.push('/login');
          return;
        }

        // 使用封装的API添加到购物车
        await cartAPI.addToCart({
          userId: user.id,
          productId: food.id,
          quantity: 1
        });

        // 重新获取购物车数据
        await this.fetchCart();
        alert('已添加到购物车');
      } catch (error) {
        console.error('添加到购物车失败:', error);
        alert('添加到购物车失败: ' + (error.message || '请稍后重试'));
      }
    }
  }
}
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0;
  color: #1890ff;
  font-size: 24px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.username {
  color: #666;
}

.logout-btn {
  padding: 6px 16px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #ff7875;
}

/* 主体内容 */
.order-content {
  padding: 20px;
}

/* 商家信息 */
.restaurant-info {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.restaurant-info h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.restaurant-desc {
  margin: 0 0 12px 0;
  color: #666;
}

.restaurant-tags {
  display: flex;
  gap: 8px;
}

.tag {
  padding: 4px 12px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

/* 菜品分类 */
.food-categories {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  overflow-x: auto;
  padding-bottom: 10px;
}

.category-btn {
  padding: 8px 20px;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 20px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.category-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.category-btn.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

/* 菜品列表 */
.food-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 80px;
}

.food-item {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.food-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.food-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.food-info {
  padding: 16px;
}

.food-name {
  margin: 0 0 8px 0;
  color: #333;
}

.food-desc {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.food-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.add-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  border: none;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background-color: #40a9ff;
}

/* 购物车底部栏 */
.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.cart-summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.cart-count {
  color: #666;
}

.cart-total {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.checkout-btn {
  padding: 10px 32px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.checkout-btn:hover {
  background-color: #ff7875;
}
</style>